package com.io.controller;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.io.dto.ApiResult;
import com.io.dto.sys.UserReq;
import com.io.dto.sys.UserRes;
import com.io.entity.SysUserEntity;
import com.io.service.SysUserService;
import com.io.utils.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * The class/interface 登录相关
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Api(tags = "登录退出")
@RestController
@RequestMapping("/sys")
public class SysLoginController {
    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("captcha.jpg")
    @ApiOperation(value = "验证码")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录接口")
    public ApiResult userLogin(@RequestBody @Validated(UserReq.Login.class) UserReq loginReq) {
        String token = sysUserService.userLogin(loginReq);
        // 用户信息（角色、项目信息）
        SysUserEntity user = sysUserService.selectByUsername(loginReq.getUsername());
        UserRes userRes = new UserRes();
        BeanUtils.copyProperties(user, userRes);
        return ApiResult.ok(userRes).token(token);
    }

    @PostMapping(value = "/logout")
    @ApiOperation(value = "退出登录")
    public ApiResult logout(HttpServletRequest request) {
        String message = sysUserService.userLogout(request);
        return ApiResult.ok(message);
    }
}
